import React, { memo, useEffect, useMemo, useState, useRef } from "react";
import {
  Modal,
  Checkbox,
  Table,
  Form,
  Input,
  InputNumber,
  Button,
  Space,
  message,
} from "antd";
import ajax from "@/services";

function EditModal(props) {
  const { visible, modalData, onCancel } = props;

  const [isDefault, setIsDefault] = useState(0);
  const isEdit = useRef(false);
  const [form] = Form.useForm();
  const [data, setData] = useState([]);
  const [editingKey, setEditingKey] = useState("");

  const [btnLoading, setBtnLoading] = useState(false);

  // checkout
  const handleChecked = (e) => {
    setIsDefault(Number(e.target.checked));
  };

  const isEditing = (record) => record.data_id === editingKey;

  const edit = (record) => {
    form.setFieldsValue({
      name: "",
      value: "",
      ...record,
    });
    setEditingKey(record.data_id);
  };

  const handleSave = (params, callback) => {
    isEdit.current = true;
    setBtnLoading(true);
    ajax
      .saveFileContent(params)
      .then(
        (res) => {
          message.success(res.message || "编辑成功");
          if (callback) {
            return callback();
          }
          const newData = [...data];
          const index = newData.findIndex(
            (item) => params.data_id === item.data_id
          );
          const item = newData[index];
          newData.splice(index, 1, {
            ...item,
            name: params.name,
            value: params.value,
          });
          setData(newData);
          setEditingKey("");
        },
        (err) => {
          !err.message && message.error("服务器异常");
        }
      )
      .finally(() => {
        setBtnLoading(false);
      });
  };

  const save = async (record) => {
    try {
      const row = await form.validateFields();
      const baseForm = {
        file_id: modalData.file_id,
        data_id: record.data_id,
        is_default: modalData.is_default,
      };
      handleSave({ ...row, ...baseForm });
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const columns = [
    {
      title: "序号",
      align: "center",
      width: 80,
      render: (val, row, index) => {
        return index + 1;
      },
    },
    {
      title: modalData.x_title || "X轴",
      dataIndex: "name",
      align: "center",
      editable: true,
      inputType: "text",
    },
    {
      title: modalData.y_title || "Y轴",
      dataIndex: "value",
      align: "center",
      editable: true,
      inputType: "number",
    },
    {
      title: "操作",
      align: "center",
      render: (val, record) => {
        const editable = isEditing(record);
        return (
          <Space>
            {editable ? (
              <>
                <Button
                  size="small"
                  type="link"
                  loading={btnLoading}
                  onClick={() => save(record)}
                >
                  保存
                </Button>
                <Button
                  size="small"
                  type="link"
                  onClick={() => setEditingKey("")}
                >
                  取消
                </Button>
              </>
            ) : (
              <Button
                size="small"
                type="link"
                disabled={editingKey !== ""}
                onClick={() => edit(record)}
              >
                编辑
              </Button>
            )}
          </Space>
        );
      },
    },
  ];

  const mergedColumns = useMemo(() => {
    return columns.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: (record) => ({
          record,
          inputType: col.dataIndex === "value" ? "number" : "text",
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(record),
        }),
      };
    });
  }, [columns]);

  useEffect(() => {
    setData(modalData.data || []);
    setIsDefault(modalData.is_default);
  }, [modalData]);

  const handleClose = () => onCancel(isEdit.current);

  const handleOnOK = () => {
    if (modalData.is_default === isDefault) return handleClose();
    handleSave(
      { file_id: modalData.file_id, is_default: isDefault },
      handleClose
    );
  };

  return (
    <Modal
      className="edit-data-modal"
      title={modalData.file_name}
      open={visible}
      width={650}
      onCancel={handleClose}
      okButtonProps={{ loading: btnLoading }}
      okText="保存"
      onOk={handleOnOK}
    >
      <div className="info-container">
        <div>图标类型：{modalData.chart_type || "--"}</div>
        <Checkbox checked={!!isDefault} onChange={handleChecked}>
          设置为首页默认图表
        </Checkbox>
      </div>
      <Form form={form} component={false}>
        <Table
          className="table-wrap"
          rowClassName="editable-row"
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          columns={mergedColumns}
          dataSource={data}
          rowKey="data_id"
          bordered
          scroll={{ y: "55vh" }}
          pagination={false}
        />
      </Form>
    </Modal>
  );
}

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `请输入${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

export default memo(EditModal);
